package com.nongtai.utils;

import com.nongtai.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author yza
 * @version 1.0
 * @date 2024/7/11 17:28
 */
@Component
public class JwtUtil {
    @Resource
    private JwtProperties jwtProperties;

    public String createJwt(Map<String, Object> payload){
        if(jwtProperties == null
        || jwtProperties.getUserTtl() == 0
        || jwtProperties.getUserSecretKey() == null
        || jwtProperties.getUserSecretKey().equals("")
        ){
            throw new RuntimeException("jwt相关配置信息错误");
        }
        if (payload == null) {
            throw new IllegalArgumentException("Payload cannot be null.");
        }
        // 签名算法
        SignatureAlgorithm hs256 = SignatureAlgorithm.HS256;
        // 头
        Map<String ,Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
                // 过期时间
        Date date = new Date(System.currentTimeMillis() + jwtProperties.getUserTtl());

        String token = Jwts.builder()
                .setHeader(header)
                .setClaims(payload)
                .setExpiration(date)
                .signWith(hs256, jwtProperties.getUserSecretKey().getBytes(StandardCharsets.UTF_8))
                .compact();

        return token;
    }

    public Claims parseJWT(String token) {
        // 得到DefaultJwtParser
        Claims claims = Jwts.parser()
                // 设置签名的秘钥
                .setSigningKey(jwtProperties.getUserSecretKey().getBytes(StandardCharsets.UTF_8))
                .build()
                // 设置需要解析的jwt
                .parseClaimsJws(token).getBody();
        return claims;
    }
}
